package me.wangcai.onlinechat.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import me.wangcai.onlinechat.manager.UserManager;
import me.wangcai.onlinechat.model.Response;
import me.wangcai.onlinechat.model.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class LoginAPIController {

    private static final Gson gson = new Gson();

    @GetMapping("/loginapi")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletRequest request){
        if(!UserManager.getUserManager().isRegister(username)){
            return gson.toJson(new Response("账号尚未注册过!",false));
        }
        if(!UserManager.getUserManager().login(username,password)){
            return gson.toJson(new Response("登录失败,密码错误!",false));
        }
        request.getSession().setAttribute("user",new User(username,request.getSession()));
        return gson.toJson(new Response("登录成功",true));
    }

    @GetMapping("/regapi")
    public String register(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletRequest request){
        if(UserManager.getUserManager().isRegister(username)){
            return gson.toJson(new Response("账号已经注册过了!",false));
        }
        UserManager.getUserManager().register(username,password);
        request.getSession().setAttribute("user",new User(username,request.getSession()));
        System.out.println(((User)request.getSession().getAttribute("user")).getUsername());
        return gson.toJson(new Response("注册成功",true));
    }
}
